import React, { useCallback, useMemo } from "react";
import { useRouter } from "next/router";
import { Tabs } from "antd";
import useMenuData from "@/hooks/useMenuData";
import { Dropdown } from "antd";
import s from "./index.module.scss";

enum OperationType {
  REFRESH = "refresh",
  CLOSE = "close",
  CLOSEOTHER = "close-other",
}

export default function TabContainer(props: { pageProps: any }) {
  const router = useRouter();

  const { tabData, activeKey, closeTab, refreshTab, closeOtherTab } =
    useMenuData();

  const menuItems: any[] = useMemo(() => {
    return [
      // {
      //   label: "刷新",
      //   key: OperationType.REFRESH,
      // },
      tabData.length <= 1
        ? null
        : {
            label: "关闭",
            key: OperationType.CLOSE,
          },
      tabData.length <= 1
        ? null
        : {
            label: "关闭其他",
            key: OperationType.CLOSEOTHER,
          },
    ].filter((o) => o);
  }, [tabData]);

  const menuClick = useCallback(
    ({ key, domEvent }: any, tab: any) => {
      domEvent.stopPropagation();

      if (key === OperationType.REFRESH) {
        refreshTab(tab.pathname);
      } else if (key === OperationType.CLOSE) {
        closeTab(tab.pathname);
      } else if (key === OperationType.CLOSEOTHER) {
        closeOtherTab(tab.pathname);
      }
    },
    [closeOtherTab, closeTab, refreshTab]
  );

  const renderTabTitle = useCallback(
    (tab: any) => {
      return (
        <Dropdown
          menu={{ items: menuItems, onClick: (e) => menuClick(e, tab) }}
          trigger={["contextMenu"]}
        >
          <div style={{ margin: "-12px 0", padding: "12px 0" }}>
            {tab.icon}
            {tab.label}
          </div>
        </Dropdown>
      );
    },
    [menuClick, menuItems]
  );

  const itemsData = useMemo(() => {
    return tabData.map((x) => {
      const Comm = x.children;
      return {
        key: x.pathname,
        label: renderTabTitle(x),
        children: (
          <div>
            <Comm {...props.pageProps} />
          </div>
        ),
      };
    });
  }, [props.pageProps, renderTabTitle, tabData]);

  const items = useMemo(() => {
    return itemsData || [];
  }, [itemsData]);

  const onChange = (newActiveKey: string) => {
    router.push(newActiveKey);
  };

  const onEdit = (targetKey: string, action: "add" | "remove") => {
    if (action === "remove") {
      closeTab(targetKey);
    }
  };

  return (
    <div className="full-w-h">
      <Tabs
        className={`full-w-h ${s["tab-container"]}`}
        type="editable-card"
        onChange={onChange}
        activeKey={activeKey}
        onEdit={onEdit as any}
        size="small"
        hideAdd
        items={items}
      />
    </div>
  );
}
